import * as login from '@/api/login'
import router from '../../router'
import Cookie from 'js-cookie'
import { setToken, removeToken } from '../../utils/auth'

const state = {
  token: '',
  username: '',
  userId: '',
  role: 0,
};

const mutations = {
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_USERNAME: (state, username) => {
    state.username = username;
  },
  SET_USERID: (state, userId) => {
    state.userId = userId;
  },
  SET_ROLE: (state, role) => {
    state.role = role;
  },
  RESET_TOKEN: (state) => {
    state.token = '';
  }
};

const actions = {
  async login({ commit }, userInfo) {
    const { username, password } = userInfo;
    try {
      const res = await login.login({username, password});
      console.log(res);
      let userData = res.msg;
      let token = res.msg.username;
      await setToken(token);
      await commit('SET_TOKEN', token);
      await commit('SET_USERNAME', userData.username);
      await commit('SET_USERID', userData.id);
      await commit('SET_ROLE', userData.role);
      Cookie.set('userInfo', JSON.stringify(state));
      router.push('/');
    } catch (e) {
      console.log(e)
    }
  },
  async resetToken({ commit }) {
    await removeToken();
    sessionStorage.removeItem('userInfo');
    await commit('RESET_TOKEN');
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions
}